package sprint.view;
/*
 Project name     : Sprint
 Project Descript : ���� �� 
 Project Manager  : Jimmy Kim
 Company          : Blue
 Class Create Day : 2014/02/07
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import sprint.doing.network.SocketOpen;
import sprint.doing.thread.InStream;
import sprint.model.FriendModel;
import sprint.model.LeciveModel;
import sprint.model.Protocal;

@SuppressWarnings("serial")
public class MineView extends JFrame implements ActionListener {
	
	public BorderLayout mainBl = new BorderLayout(5,5);
	public BorderLayout cenMain = new BorderLayout(5,5);
	public LoginView login= new LoginView();
	public TalkView talk ;
	public JPanel mainPanel = new JPanel(cenMain);
	
	private JDialog friendAddJD = new JDialog(this,"친구 추가 화면",false);
	private BorderLayout dialogMainLayout = new BorderLayout(5,5);
	private JPanel dialogPanel = new JPanel(dialogMainLayout);
	private JButton [] serchFriend;
	private JLabel [] serchFriendLb;
	private JTextField inputId = new JTextField(10);
	private JButton serchButton = new JButton("검색");
	private JLabel message = new JLabel("ID를 입력하세요",JLabel.CENTER);
	
	
	public JButton [] friend ;
	public JButton  friendinsert = new JButton("친구 추가");
	public JLabel [] friendState ;
	
	//=================================================================
	SocketOpen so;
	Socket socket;
	OutputStream os;
	InputStream is;
	BufferedWriter bw ;
	BufferedReader br;
	//OutStream outStream ;
	InStream inStream;
	
	public String resultSoket;
	ArrayList<LeciveModel> sendTr;
	ArrayList<FriendModel> friendList;
	
	
	public MineView(){
		super("You & I Talk");
		sendTr = new ArrayList<LeciveModel>();
		friendList = new ArrayList<FriendModel>();
		so = new SocketOpen(); 
	    grideView();
	    leadySoket();	
	    friendAdd();
	    talk = new TalkView();
	    actionRun();
	    
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
	}

	private void leadySoket() {
		// TODO Auto-generated method stub
		 so = new SocketOpen(); 
		 resultSoket = so.socketStart();
		 if(resultSoket.equals("false")){
			 JOptionPane.showMessageDialog(this,"서버와 연결되지 않았습니다.","네트워크 에러",JOptionPane.INFORMATION_MESSAGE);
		 }else{
			 socket= so.getSocket();
			 try{
				 os = socket.getOutputStream();
				 is = socket.getInputStream();
				 bw = new BufferedWriter(new OutputStreamWriter(os));
				 br = new BufferedReader(new InputStreamReader(is));
		//		 outStream = new OutStream(bw, sendTr);
		//		 outStream.start();
				 inStream = new InStream(br,friendList,this);
				 inStream.start();
 
			 }catch(Exception e){}
		 }
	}

	private void grideView() {
		// TODO Auto-generated method stub
		
		setLayout(mainBl);
	
		mainPanel.setBackground(Color.WHITE);
		this.add("Center",mainPanel) ;
		mainPanel.add("North", new JLabel(" "));
		mainPanel.add("South", new JLabel("Copy Write BLUE STUDIO                                  Making by KMH"));
		mainPanel.add("East", new JLabel("  "));
		mainPanel.add("West", new JLabel("  "));

		login.setBackground(Color.WHITE);
		mainPanel.add("Center",login);
			
		setSize(400,600);
		Dimension mys = this.getSize();
		Dimension src = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation(src.width/2-mys.width/2,src.height/2-mys.height/2);
		this.setAlwaysOnTop(true);
		setVisible(true);
	}

	public void actionRun(){
		login.login.addActionListener(this);
		login.join.addActionListener(this);
		login.joinbt.addActionListener(this);
		friendinsert.addActionListener(this);
		serchButton.addActionListener(this);
	}

	private void friendListShow() {
		// TODO Auto-generated method stub
		mainPanel.removeAll();
		mainPanel.updateUI();
		friend = new JButton[friendList.size()];
		friendState = new JLabel[friendList.size()];
		mainPanel.add("North", new JLabel(" "));
		mainPanel.add("South", new JLabel("Copy Write BLUE STUDIO                                 Making by KMH"));
		mainPanel.add("East", new JLabel("  "));
		mainPanel.add("West", new JLabel("  "));
		
		if(friendList.size() > 0){
			JPanel flist = new JPanel(new GridLayout(friendList.size(),2));
			mainPanel.add("Center",flist);
			flist.setBackground(Color.white);
		
			for(int i=0;i<friendList.size();i++){
				friend[i] = new JButton(friendList.get(i).getFriendName());
				if(friendList.get(i).getFriendState() == 0){
					friendState[i] = new JLabel("로그인");
				}else{
					friendState[i] = new JLabel("로그아웃");
				}
				flist.add(friend[i]);
				flist.add(friendState[i]);
			}
		}else{
			JPanel flist = new JPanel(new FlowLayout(1));
			mainPanel.add("Center",flist);
			flist.setBackground(Color.white);
			flist.add(new JLabel("등록된 친구가 없습니다."));
			flist.add(friendinsert);
		}
	}
	
	private void friendAddSerch(){
		dialogPanel.removeAll();
		dialogPanel.updateUI();
	}
	
	private void friendAdd() {
		friendAddJD.setLayout(new BorderLayout(5,5));
		friendAddJD.setBackground(Color.white);
		friendAddJD.add("North",new JLabel("   "));
		friendAddJD.add("South",new JLabel("   "));
		friendAddJD.add("East",new JLabel("   "));
		friendAddJD.add("West",new JLabel("   "));
		friendAddJD.add("Center",dialogPanel);
		dialogPanel.setBackground(Color.white);
		dialogPanel.setLayout(dialogMainLayout);
		dialogPanel.add("North",new JLabel("    "));
		JPanel ent = new JPanel();
		ent.setBackground(Color.white);
		dialogPanel.add("Center",ent);
		dialogPanel.add("South",new JLabel("    "));
		
		ent.setLayout(new GridLayout(2,1));
		ent.add(message);
		JPanel ent2 = new JPanel();
		ent2.setBackground(Color.white);
		ent2.setLayout(new FlowLayout(2));
		ent.add(ent2);
		ent2.add(inputId);
		ent2.add(serchButton);

		friendAddJD.setSize(300, 300);
		Dimension mys = friendAddJD.getSize();
		Dimension src = Toolkit.getDefaultToolkit().getScreenSize();
		friendAddJD.setLocation(src.width/2-mys.width/2,src.height/2-mys.height/2);
		friendAddJD.setResizable(false);

	}

	private void talkViewLoding() {
		// TODO Auto-generated method stub
		talk.setVisible(true);

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == login.login){	
			String pwtext = login.ipuPw.getText().trim();
			String idtext = login.iputId.getText().trim();		
			if(idtext.equals("")){
				JOptionPane.showMessageDialog(this," ID를 입력하세요 ","입력오류",JOptionPane.INFORMATION_MESSAGE);
			}else if(pwtext.equals("")){
				JOptionPane.showMessageDialog(this," PW를 입력하세요 ","입력오류",JOptionPane.INFORMATION_MESSAGE);
			}else if(!idtext.equals("") & !pwtext.equals("")){
				this.setEnabled(false);
	
			    String tran = "Protocal:"+Protocal.login +":ID:"+idtext +":Pass:"+pwtext;
				try{

					bw.write(tran+"\n");
					bw.flush();

					System.out.println("서버에 전송하였습니다.");
				}catch(Exception ee){
					System.out.println("서버에 전송실패 하였습니다.");
					System.out.println("에러메시지 " +ee.toString());
				}
				try{
					Thread.sleep(1000);
				}catch(Exception ex){}
				
			    	if(inStream.check == 1){
			    		JOptionPane.showMessageDialog(this," 로그인 되었습니다 ","로그인성공",JOptionPane.INFORMATION_MESSAGE);
			    		friendListShow();
			    		this.setEnabled(true); 	
			    		
			    		//talkViewLoding();
			    	}else if(inStream.check == 2){
			    		JOptionPane.showMessageDialog(this," 로그인에 실패 하였습니다 ","로그인오류",JOptionPane.INFORMATION_MESSAGE);
			    		this.setEnabled(true);
			    		 login.ipuPw.setText("");
					     login.iputId.setText("");	
			    	}	
			}
		}
		
		if(e.getSource() == login.join){
			login.joinDialog.setVisible(true);

		}
		if(e.getSource() == login.joinbt){
			String id = login.joinInId.getText().trim();
			String pw = login.joinInPw.getText().trim();
			String tran = "Protocal:"+Protocal.join +":ID:"+id +":Pass:"+pw;
			try{ 
				bw.write(tran+"\n");
				bw.flush();
				System.out.println("서버에 전송하였습니다.");
			}catch(Exception eee){
				System.out.println("서버에 전송실패 하였습니다.");
				System.out.println("에러메시지 " +eee.toString());
			}
		}
		
		if(e.getSource() == friendinsert){
			friendAddJD.setVisible(true);
		}
		
		if(e.getSource() == serchButton ){
			String frid = inputId.getText().trim();
			
			if(frid.equals("")){
				JOptionPane.showMessageDialog(this," ID를 입력하세요 ","입력오류",JOptionPane.INFORMATION_MESSAGE);
			}else{
				
				String tran = "Protocal:"+Protocal.serch +":ID:"+frid;
				try{ 
					bw.write(tran+"\n");
					bw.flush();
					System.out.println("서버에 전송하였습니다.");
				}catch(Exception eee){
					System.out.println("서버에 전송실패 하였습니다.");
					System.out.println("에러메시지 " +eee.toString());
				}	
				for(int i=0; i<10;i++){

					try{
						Thread.sleep(1000);
						if(inStream.serchReshult != null){
							for(int j=0; j>inStream.serchReshult.length;j++){
								System.out.println("검색된 친구 목록"+inStream.serchReshult[j]);
							}
								break;
						}else{
							System.out.println("전송 확인중...."+i);
						}
					}catch(Exception ex){}
					
				}
			}
		}
	}

}

